package com.zzy.demo.web;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.zzy.demo.entity.Order;
import com.zzy.demo.entity.Order.OrderDetailView;
import com.zzy.demo.entity.Order.OrderSimpleView;

@RestController
@RequestMapping("/order")
public class RestOrderApiCrontroller {
	
	
	@GetMapping()
	@JsonView(OrderSimpleView.class)
	public List<Order> getOrder(Order queryOrder) throws Exception{
		
		System.out.println("------------"+queryOrder.getName()+"--------------");
		
		Order order = new Order();
		order.setId("O170501-1");
		order.setName("订单名称");
		
		Order order2 = new Order();
		order2.setId("O170501-1");
		order2.setName("订单名称");
		
		List<Order> list = new ArrayList<Order>();
		list.add(order);
		list.add(order2);
		return list;
	}
	
	

	@GetMapping("/{orderId:\\d+}")  //  正则表达式 只能接收数字
	//@GetMapping("/orderId}")
	@JsonView(OrderDetailView.class)
	public Order getOrder(@PathVariable(name="orderId") String orderId) throws Exception{
		Order order = new Order();
		order.setId("O170501-"+orderId);
		order.setName("name-"+orderId);
		return order;
	}
	
	
	
	

	
	@PostMapping()
	public Order addOrder(@Valid @RequestBody Order order,BindingResult errors) throws Exception{
		//处理错误信息
		if(errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error->System.out.println(error.getDefaultMessage()));
		}
		
		return order;
	}
	
	
	@PostMapping("/orders")
	public String batchAdd(@RequestBody List<Order> order) throws Exception{
		return "{success:true,message:\"批量添加成功\"}";
	}
	
	
	@PutMapping("/{orderId}")
	public Order updateOrder(@Valid @RequestBody Order order, BindingResult errors) throws Exception {
		// 处理错误信息
		if (errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error -> {
				FieldError fieldError=(FieldError) error;
				System.out.println(fieldError.getField()+"--------"+error.getDefaultMessage());
			});
		}

		return order;
	}
	
	
	@DeleteMapping("/{orderId}")
	public String deleteOrder(@PathVariable(name="orderId") String orderId) throws Exception{
		System.out.println(orderId);
		return "{\"success\":true,\"message\":\"订单取消成功\"}";
	}
	
}
